package com.wjc.server.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wjc.server.dto.PageDto;
import com.wjc.server.dto.TeacherDto;
import com.wjc.server.entity.Teacher;
import com.wjc.server.entity.TeacherExample;
import com.wjc.server.mapper.TeacherMapper;
import com.wjc.server.util.CopyUtil;
import com.wjc.server.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;


@Service
public class TeacherService {
    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private SnowFlake snowFlake;

    //查询
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        TeacherExample teacherExample = new TeacherExample();
        List<Teacher> teacherList= teacherMapper.selectByExample(teacherExample);
        PageInfo<Teacher> pageInfo=new PageInfo<>(teacherList);
        pageDto.setTotal(pageInfo.getTotal());

        List<TeacherDto> teacherDtosList = CopyUtil.copyList(teacherList,TeacherDto.class);
        pageDto.setList(teacherDtosList);

    }

    //保存
    public void save(TeacherDto teacherDto){

        Teacher teacher=CopyUtil.copy(teacherDto,Teacher.class);
        if (ObjectUtils.isEmpty(teacher.getId())){
            //新增
            teacher.setId(snowFlake.nextId());
            teacherMapper.insert(teacher);
        }else {
            teacherMapper.updateByPrimaryKey(teacher);
        }

    }

    public void delete(Long id){
        teacherMapper.deleteByPrimaryKey(id);
    }

    //查所有数据
    public List<TeacherDto> all( ){
        TeacherExample teacherExample=new TeacherExample();
        List<Teacher> teacherList= teacherMapper.selectByExample(teacherExample);
        List<TeacherDto> teacherDtoList = CopyUtil.copyList(teacherList,TeacherDto.class);
        return teacherDtoList;
    }

    /**
     * 查找
     * @param id
     */
    public TeacherDto findById(Long id) {
        Teacher teacher = teacherMapper.selectByPrimaryKey(id);
        return CopyUtil.copy(teacher, TeacherDto.class);
    }

}
